package com.fowo.api.documentCirculation.sql;

/**
 * MySql 语法处理器
 * @author yl_ls
 */
public class MySqlHandler extends AbsoluteSqlHandler {
    @Override
    public String safeName(String name) {
        if (name.startsWith("`")) {
            return name;
        }
        return "`" + name + "`";
    }

    @Override
    protected void appendSelectEnd(StringBuilder sb, SqlBuilder sqlBuilder) {
        if (sqlBuilder.getLimit() != null) {
            if (sqlBuilder.getSkip() != null) {
                sb.append(String.format(" LIMIT %d, %d", sqlBuilder.getSkip(), sqlBuilder.getLimit()));
            } else {
                sb.append(String.format(" LIMIT %d", sqlBuilder.getLimit()));
            }
        } else if (sqlBuilder.getSkip() != null) {
            sb.append(String.format(" OFFSET %d", sqlBuilder.getSkip()));
        }
    }

    @Override
    protected void appendConvertToStringEnd(StringBuilder sb) {
        sb.append(" AS CHAR(20))");
    }

    @Override
    protected void appendConvertToStringStart(StringBuilder sb) {
        sb.append("CAST(");
    }

    @Override
    public SqlAndArgs getSelectExistsSql(SqlBuilder sqlBuilder) throws Exception {
        SqlAndArgs sqlAndArgs = getSql(sqlBuilder);
        sqlAndArgs.setSql(String.format("SELECT if(EXISTS (%s), 1, 0) FROM DUAL", sqlAndArgs.getSql()));
        return sqlAndArgs;
    }

    @Override
    public String getNewIdentitySql() {
        return "SELECT last_insert_id() as id";
    }

    @Override
    protected Object convertToSqlArg(Object conditionValue) {
        if (conditionValue != null && conditionValue.getClass().equals(Boolean.class)) {
            return (boolean)conditionValue ? 1 : 0;
        }
        return super.convertToSqlArg(conditionValue);
    }
}
